<?php
declare (strict_types=1);

namespace app\command;

use app\common\loader\ModelMerchant;
use app\common\loader\ModelShop;
use app\common\loader\ModelVirtual;
use think\console\Command;
use think\console\Input;
use think\console\Output;

/**
 * 商户统计
 */
class Statistic extends Command
{


    protected function configure()
    {
        // 指令配置
        $this->setName('statistic')
            ->setDescription('统计信息');
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $where_time = $this->actionStatisticWhere();
        $statisticData['day'] = $this->actionStatisticData($where_time, 'day');
        $statisticData['month'] = $this->actionStatisticData($where_time, 'month');
        $this->actionStatisticDataAdd($statisticData);
        $output->writeln('统计信息');
    }


    /**
     * 统计数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\Exception
     */
    public function actionStatisticData($where, $date)
    {
        $result = [
            'mer_id' => 0,
            'status' => 1, //是否禁用，2禁用，1启动
            'op_user' => 0, //所属管理员
            'account_money' => 0, //账号金额
            'recharge_money' => '0', //充值金额
            'type' => 1, //是否是沉睡用户2沉睡，1启动
            'create_at' => date('Y-m-d') . ' 23:59:59', //时间
            'code_number' => '0', //扫码数量
            'manager_num' => '0', //导购数量
            'manager_red_packet' => '0', //导购发出红包
            'manager_point' => '0', //导购发出积分
        ];

        if ((string)$date === 'day') {
            $where['where_time'] = $where['day'];
            $where['order_where'] = $where['order_day_where'];
            $statistics_create = $where['statistics_create_day'];
        }


        if ((string)$date === 'month') {
            $where['where_time'] = $where['month'];
            $where['order_where'] = $where['order_month_where'];
            $statistics_create = $where['statistics_create_month'];
        }

        $merchantModel = ModelMerchant::Merchant();//商户信息表
        $shopSalesmanModel = ModelShop::ShopSalesman();//导购表
        $promoUsedLogModel = ModelVirtual::VirtualUsedLog();//虚码使用记录表
        $merchantOrderPointModel = ModelMerchant::MerchantOrderPoint();//积分商城订单表
        $merchantMoneyModel = ModelMerchant::MerchantStock(); //商户余额表
        $merchantMoneyLogModel = ModelMerchant::RechargeLog(); //商户充值表t_recharge_log
        $MerchantList = $merchantModel->MerchantList($where['merchantWhere']);
        if (empty($MerchantList)) {
            return [];
        }
        $ShopSalesman = $shopSalesmanModel->shopSalesmanList();
        $MerchantOrderPoint = $merchantOrderPointModel->promoUsedOrderList($where['where_time']);
        $PromoUsedLog = $promoUsedLogModel->promoUsedLogList($where['order_where']);
        $MerchantMoneyLog = $merchantMoneyLogModel->rechargeMoneyList($where['where_time']);
        $MerchantMoney = $merchantMoneyModel->column([], 'balance', 'mer_id');
        //一周内无充值，无扫码
        $Manger_num = $promoUsedLogModel->removeOption()->promoUsedLogNum($where['week']);
        $Money_num = $merchantMoneyLogModel->removeOption()->rechargeMoneyNum($where['week']);
        foreach ($MerchantList as $key => $v) {
            $MerchantList[$key]['account_money'] = $MerchantMoney[$v['mer_id']] ?? $result['account_money'];
            $MerchantList[$key]['recharge_money'] = $MerchantMoneyLog[$v['mer_id']] ?? $result['account_money'];
            $MerchantList[$key]['type'] = $result['type'];//是否是沉睡用户2沉睡，1启动
            if ((($Manger_num[$v['mer_id']] ?? 0) + ($Member_num[$v['mer_id']] ?? 0) + ($Money_num[$v['mer_id']] ?? 0)) < 1) {
                $MerchantList[$key]['type'] = 2;//是否是沉睡用户2沉睡，1启动
            }
            $MerchantList[$key]['create_at'] = $result['create_at'];
            $MerchantList[$key]['manager_num'] = $ShopSalesman[$v['mer_id']] ?? $result['manager_num'];
            $MerchantList[$key]['manager_red_packet'] = $PromoUsedLog[$v['mer_id']]['red_packet'] ?? $result['manager_red_packet'];
            $MerchantList[$key]['code_number'] = ($PromoUsedLog[$v['mer_id']]['order_sum'] ?? 0) + ($PromoUsedLogMember[$v['mer_id']]['order_sum'] ?? 0) ?? $result['code_number'];
            $MerchantList[$key]['manager_point'] = ($PromoUsedLog[$v['mer_id']]['point'] ?? 0) + ($MerchantOrderPoint[$v['mer_id']]['manager_point'] ?? 0) ?? $result['manager_point'];
            $MerchantList[$key]['statistics_date'] = $statistics_create;
        }
        return $MerchantList;
    }

    //调用实例条件
    private function actionStatisticWhere()
    {
        $result = [
            'day' => [],//天
            'month' => [],//月
            'week' => [],//周
            'merchantWhere' => ['is_manager' => '1'], //商户超级管理员
            'promoUsedWhere' => [], //导购扫码表
            'promoUsedLogMember' => [], //会员扫码表
            'statistics_create_day' => '', //获取当前日
            'statistics_create_month' => '', //获取当前月
            'order_month_where' => '', //虚码使用记录
            'order_day_where' => '', //虚码使用记录
        ];


        $result['day'] = $this->actionWhere('day', 'create_at');
        $result['month'] = $this->actionWhere('month', 'create_at');
        $result['order_month_where'] = $this->actionWhere('month', 'update_at');
        $result['order_day_where'] = $this->actionWhere('day', 'update_at');
        $result['week'] = $this->actionWhere('week', 'create_at');
        $result['statistics_create_day'] = date('Y-m-d',strtotime('-1 day'));
        $result['statistics_create_month'] = date('Y-m');
        return $result;
    }

    private function actionWhere($date, $filed)
    {
        $time = date('Y-m-d',strtotime('-1 day'));
        switch ($date) {
            case 'day':
                $etime = $time . ' 23:59:59';
                $stime = $time . ' 00:00:00';
                break;
            case 'month':
                $stime = date('Y-m-01', strtotime($time)) . ' 00:00:00';
                $etime = $time . ' 23:59:59';
                break;
            case 'week':
                $etime = $time . ' 23:59:59';
                $stime = date("Y-m-d", strtotime('-7 day')) . ' 00:00:00';
                break;
            default:
                $etime = $time . ' 23:59:59';
                $stime = $time . ' 00:00:00';
                break;
        }
        return [[$filed, 'between', [$stime, $etime]]];
    }

    //添加
    private function actionStatisticDataAdd($data = []): void
    {
        ModelMerchant::MerchantStatistic()->add('merchant_statistic_day', $data['day']);
        if (!empty($data['month'])) {
            ModelMerchant::MerchantStatistic()->add('merchant_statistic_month', $data['month']);
        }
    }
}
